"""
PicknBuy24列表页提取器 - 基于真实HTML结构
"""
import re
from typing import List, Dict, Any
from bs4 import BeautifulSoup
from urllib.parse import urljoin

from axiom_boot.logging.setup import get_logger
from axiom_boot.scraper.interfaces import Extractor
from axiom_boot.scraper.models import Response, Target, Item

logger = get_logger(__name__)


class VehicleUrlItem(Item):
    """车辆URL项目 - 增强版，包含价格和折扣信息"""
    url: str
    ref_no: str
    title: str = ""
    year: str = ""
    make: str = ""
    model: str = ""
    mileage: str = ""
    vehicle_type: str = ""  # 车辆类型
    
    # 增量更新需要的价格信息
    price_current: str = ""  # 当前价格文本 (如: "US$ 3,040")
    price_before_discount: str = ""  # 折扣前价格文本 (如: "US$ 3,090")
    discount_amount: str = ""  # 折扣金额文本 (如: "US$ 50")
    has_discount: bool = False  # 是否有折扣
    status_tags: list = []  # 状态标签 (如: ["SALE", "NEW"])


class ListPageExtractor(Extractor):
    """PicknBuy24列表页提取器 - 基于真实HTML结构"""

    def extract(self, response: Response, target: Target) -> List[Item]:
        """
        提取车辆详情页URL列表和基本信息 - 基于真实HTML结构
        
        Returns:
            List[VehicleUrlItem]: 车辆URL项目列表
        """
        try:
            soup = BeautifulSoup(response.text, "html.parser")
            base_url = "https://www.picknbuy24.com"
            
            logger.info(f"开始提取PicknBuy24车辆URL列表...")
            vehicle_items = []
            
            # 根据真实HTML结构：查找 #carList 容器下的 .carBox
            car_list = soup.find('div', id='carList')
            if not car_list:
                logger.warning("未找到#carList容器")
                return []
            
            # 查找所有车辆盒子
            car_boxes = car_list.find_all('div', class_='carBox')
            logger.info(f"找到 {len(car_boxes)} 个车辆盒子")
            
            for car_box in car_boxes:
                try:
                    # 1. 从 carImg 中提取详情页链接和ref_no
                    car_img = car_box.find('div', class_='carImg')
                    if not car_img:
                        continue
                    
                    detail_link = car_img.find('a', href=re.compile(r'refno=\d+'))
                    if not detail_link:
                        continue
                    
                    href = detail_link.get('href', '')
                    ref_match = re.search(r'refno=(\d+)', href)
                    if not ref_match:
                        continue
                    
                    ref_no = ref_match.group(1)
                    full_url = urljoin(base_url, href)
                    
                    # 2. 从 carInfo > carName 中提取标题信息
                    car_info = car_box.find('div', class_='carInfo')
                    if not car_info:
                        continue
                    
                    car_name = car_info.find('div', class_='carName')
                    if car_name:
                        # 提取ref_no（验证）
                        refno_div = car_name.find('div', class_='refno')
                        if refno_div:
                            refno_text = refno_div.get_text(strip=True)

                        
                        # 提取车辆名称
                        h2_tag = car_name.find('h2')
                        if h2_tag:
                            title_link = h2_tag.find('a')
                            title = title_link.get_text(strip=True) if title_link else h2_tag.get_text(strip=True)
                        else:
                            title = ""
                    else:
                        title = ""
                    
                    # 解析年份、品牌、型号
                    year, make, model = self._parse_title(title)
                    
                    # 3. 从表格中提取里程信息
                    table = car_info.find('table')
                    mileage = ""
                    if table:
                        # 查找里程信息
                        for td in table.find_all('td'):
                            td_text = td.get_text(strip=True)
                            if 'km' in td_text.lower():
                                mileage = td_text
                                break
                    
                    # 4. 提取价格和折扣信息
                    price_current, price_before_discount, discount_amount, has_discount = self._extract_price_info(car_info)
                    
                    # 5. 提取状态标签
                    status_tags = self._extract_status_tags(car_box)
                    
                    # 6. 提取车辆类型（从URL）
                    vehicle_type = self._extract_vehicle_type_from_url(response.url)
                    
                    # 创建项目（增强版 - 包含价格信息）
                    item = VehicleUrlItem(
                        url=full_url,
                        ref_no=ref_no,
                        title=title,
                        year=year,
                        make=make,
                        model=model,
                        mileage=mileage,
                        vehicle_type=vehicle_type,
                        price_current=price_current,
                        price_before_discount=price_before_discount,
                        discount_amount=discount_amount,
                        has_discount=has_discount,
                        status_tags=status_tags
                    )
                    
                    vehicle_items.append(item)

                    
                except Exception as e:
                    logger.warning(f"处理车辆盒子时出错: {e}")
                    continue
            
            logger.info(f"成功提取到 {len(vehicle_items)} 个车辆URL")
            return vehicle_items
            
        except Exception as e:
            logger.error(f"PicknBuy24列表页提取失败: {e}")
            return []
    
    def _parse_title(self, title: str) -> tuple:
        """解析标题获取年份、品牌、型号"""
        try:
            # 格式: "2014 HONDA FIT HYBRID"
            parts = title.strip().split()
            if len(parts) >= 3:
                year = parts[0] if parts[0].isdigit() and len(parts[0]) == 4 else ""
                make = parts[1] if len(parts) > 1 else ""
                model = " ".join(parts[2:]) if len(parts) > 2 else ""
                return year, make, model
            return "", "", title
        except Exception:
            return "", "", title
    

    
    def _extract_price_info(self, car_info) -> tuple:
        """提取价格和折扣信息 - 基于真实HTML结构"""
        try:
            price_current = ""
            price_before_discount = ""
            discount_amount = ""
            has_discount = False
            
            # 根据真实HTML结构：查找 .carPrice .price .fob
            car_price_div = car_info.find('div', class_='carPrice')
            if not car_price_div:
                return "", "", "", False
            
            price_div = car_price_div.find('div', class_='price')
            if not price_div:
                return "", "", "", False
            
            fob_div = price_div.find('div', class_='fob')
            if not fob_div:
                return "", "", "", False
            
            # 提取当前价格：<b>US$ 850</b>
            price_b = fob_div.find('b')
            if price_b:
                price_current = price_b.get_text(strip=True)
            
            # 提取原价：<span class="original">$900</span>
            original_span = fob_div.find('span', class_='original')
            if original_span:
                price_before_discount = original_span.get_text(strip=True)
            
            # 提取折扣：<span class="clearance">-$50</span>
            clearance_span = fob_div.find('span', class_='clearance')
            if clearance_span:
                discount_amount = clearance_span.get_text(strip=True)
                has_discount = True
            
            # 如果有原价但没有折扣标识，也认为有折扣
            if price_before_discount and not has_discount:
                has_discount = True
            
            return price_current, price_before_discount, discount_amount, has_discount
            
        except Exception as e:
            logger.error(f"提取价格信息失败: {e}")
        return "", "", "", False
    
    def _extract_status_tags(self, car_box) -> list:
        """提取状态标签 - 基于真实HTML结构"""
        try:
            status_tags = []
            
            # 只检测实际存在的2个页面标签
            # <span class="iconSale"></span> 表示打折
            if car_box.find('span', class_='iconSale'):
                status_tags.append('SALE')
            
            # <span class="iconNew"></span> 表示新上
            if car_box.find('span', class_='iconNew'):
                status_tags.append('NEW')
            
            # 注意：normal状态表示无任何标签，sold状态由我们计算
            

            return status_tags
            
        except Exception as e:

            return []
    
    def _extract_vehicle_type_from_url(self, url: str) -> str:
        """从URL参数中提取车辆类型"""
        try:
            from urllib.parse import urlparse, parse_qs
            parsed = urlparse(url)
            params = parse_qs(parsed.query)
            
            type_param = params.get('type', [''])[0].upper()
            valid_types = ['SEDAN', 'SUV', 'WAGON', 'COMPACT', 'SPORTY', 'TRUCK', 'VAN', 'SPECIAL']
            
            return type_param if type_param in valid_types else ""
        except Exception:
            return ""